package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class UploadController {

    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info("接收到前端传来的文件:{}",file);
        try {
            String fileName = file.getOriginalFilename();
            String first = UUID.randomUUID().toString();
            String last = fileName.substring(fileName.lastIndexOf("."));
            String photoName = first + last;
            File filedir = new File(path);
            if (!filedir.exists()){
                filedir.mkdirs();
            }
            file.transferTo(new File(path+photoName));
            return R.success(photoName);

        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
          log.info("上传数据");
        try {
            FileInputStream fis = new FileInputStream(path+name);
            ServletOutputStream outputStream = response.getOutputStream();

            int len;
            byte[] b = new byte[1024];
            while ((len = fis.read(b)) != -1){
                outputStream.write(b,0,len);
            }
            outputStream.close();
            fis.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
